/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
 */

package com.jinhe.tss.component.dynproperty.entity;

import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import com.jinhe.tss.component.dynproperty.DynConstants;
import com.jinhe.tss.core.exception.BusinessException;
import com.jinhe.tss.core.persistence.IEntity;
import com.jinhe.tss.core.util.BeanUtil;
import com.jinhe.tss.core.util.DateUtil;
import com.jinhe.tss.core.web.dispaly.tree.ITreeNode;
import com.jinhe.tss.core.web.dispaly.tree.TreeAttributesMap;
import com.jinhe.tss.core.web.dispaly.xform.IXForm;

/** 
 * <p> Propertydef.java </p> 
 * 
 * @author Jon.King 2008/04/14 10:18:10  
 * 
 * 自定义属性表
 * 唯一索引：entityCode, key
 */
@Entity
@Table(name = "component_dyn_propertydef", uniqueConstraints = { 
        @UniqueConstraint(name="MULTI_NAME_PROPERTY_DEF", columnNames = { "entityCode", "name" }),
        @UniqueConstraint(name="MULTI_CODE_PROPERTY_DEF", columnNames = { "entityCode", "key" }) 
    })
@SequenceGenerator(name = "dyn_def_sequence", sequenceName = "dyn_def_sequence", initialValue = 1000, allocationSize = 10)
public class PropertyDef implements IEntity, IXForm, ITreeNode {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "dyn_def_sequence")
    private Long    id;            //自定义属性ID 　主键
    private String  entityCode;   //对应的实体类型code，在导入基本属性时在配置文件中设定，用来唯一标识不同动态对象
    private String  entityName;  //对应的实体名称 （类名）
    private Integer seqNo;      //显示顺序    
    private String  name;      //名称  
    private String  key;      //字段名称（E) 
    private String  type;    //类型    1:文本 2:日期 3:数字 4:大字段 5:上传文件 6: 密码
    private String  editor; //编辑器  0:文本框 1:多行文本框 2:下拉列表 3:单选框
    private Integer length; //长度  
    private String  format; //格式化 
    private String  verify; //校验  
    private String  remark; //备注  
    
    @Column(name="option_", length = 4000)  
    private String  option ; //选项（值域）  
    private String  defaultValue ; //默认值 
    private Integer allowNull ;   //是否可空   
    private Integer allowMulti ; //是否多值    　
    
    private Integer isdyn = new Integer(0);      //判断是动态属性还是基本属性  0:基本属性 1：动态属性
    private Integer isHidden = new Integer(0);   //该属性是否隐藏     0:显示 1：隐藏
    private Integer isSpare = new Integer(0);    //是否是备用属性     0:备用 1：启用

    public boolean isdyn(){ return new Integer(1).equals(isdyn); }
    public boolean isHidden(){ return new Integer(1).equals(isHidden); }
    public boolean isSpare(){ return new Integer(1).equals(isSpare); }
    public boolean isAllowingNull(){ return new Integer(1).equals(allowNull); }
    public boolean isAllowingMulti(){ return new Integer(1).equals(allowMulti); }
        
    public Map<String, Object> getAttributesForXForm() {
        Map<String, Object> map = new HashMap<String, Object>();
        BeanUtil.addBeanProperties2Map(this, map);
        return map;
    }
    
    public TreeAttributesMap getAttributes() {
        TreeAttributesMap map = new TreeAttributesMap(id, name);
        map.put("type", DynConstants.PROPERTY_TYPE);
        map.put("isdyn", this.isdyn);
        map.put("isSpare", this.isSpare);
        if(isSpare()){
            if(this.key.startsWith("spareLong")) {
                map.put("icon", "images/backup_num.gif");
            }
            if(this.key.startsWith("spareStr")) {
                map.put("icon", "images/backup_chr.gif");
            }
            if(this.key.startsWith("spareDate")) {
                map.put("icon", "images/backup_time.gif");
            }
        }
        else{
            map.put("icon", "images/" + (new Integer(1).equals(isdyn) ? "d" : "") + "property.gif");
        }
        
        return map;
    }
    
    public String genMode(){
        if(isHidden()){
            return "\"hidden\"";
        }
        
        switch(type.charAt(0)){
        case '1':
        case '4':
        case '5':
        case '6':
            return "\"string\"";
        case '2':
            return "\"date\"" + (this.format == null ? " pattern=\"" + DateUtil.DEFAULT_DATE_PATTERN + "\"" : "");
        case '3':
            return "\"number\"";
        default:
            throw new BusinessException("动态属性type值有误！");
        }
    }
    
    public String genEditor(){
        if(type.equals("6"))
            return " editor=\"password\"";
        if(type.equals("4"))
            return " editor=\"textarea\"";
        if(type.equals("2") || type.equals("3") || type.equals("5") )
            return " editor=\"text\"";
        
        StringBuffer sb = new StringBuffer();
        switch(this.editor.charAt(0)){
        case '0':
            return " editor=\"text\"";
        case '1':
            return " editor=\"textarea\"";
        case '2':
            sb.append(" editor=\"comboedit\"").append(genOption());            
            break;
        case '3':
            sb.append(" editor=\"radio\"").append(genOption());            
            break;
        }
        return sb.toString();
    }
    
    private String genOption(){
        StringBuffer sb = new StringBuffer();
        if(this.option != null){
            StringBuffer editorvalue = new StringBuffer();
            StringBuffer editortext = new StringBuffer();
            
            StringTokenizer stk = new StringTokenizer(this.option.trim());
            while(stk.hasMoreTokens()){
                String oneOption = stk.nextToken();  
                Object[] objs = oneOption.split("/");
                if(objs.length != 2){
                    throw new BusinessException("动态属性：【" + this.name + "】 值域：【" + this.option + "】格式不正确，请修改后在操作");
                }
                if(editorvalue.length() > 0){
                    editorvalue.append("|");
                    editortext.append("|");
                }
                editorvalue.append(objs[0]);
                editortext.append(objs[1]);
            }
            sb.append(" editorvalue=\"").append(editorvalue).append("\"");
            sb.append(" editortext=\"").append(editortext).append("\"");
        }
        return sb.toString();
    }
    
    public String genColumn(){
        StringBuffer sb = new StringBuffer("<column ");   
        sb.append("name=\"").append(this.key);
        sb.append("\" caption=\"").append(this.name).append("\" mode=").append(this.genMode());
        if(!isHidden()) {
            sb.append(" empty=").append(isAllowingNull() ? "\"true\"" : "\"false\"");
        }
        if(isAllowingMulti()){
            sb.append(" multiple=\"true\"");
        }
        if(this.format != null){
            sb.append(" pattern=\"").append(this.format).append("\"");
        }
        if(this.length != null){
            sb.append(" maxLength=\"").append(this.length).append("\"");
        }
        if(this.verify != null){
            sb.append(" inputReg=\"").append(this.verify).append("\"");
        }        
        if(this.defaultValue != null){
            sb.append(" defaultValue=\"").append(this.defaultValue).append("\"");
        }        
        sb.append(genEditor());
        return sb.append(" />").toString();
    }
    
    public String genDynKey(){
        return "dynpropertiesMap['" + this.key + "']";
    }
    
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getEntityCode() {
        return entityCode;
    }
    public void setEntityCode(String entityCode) {
        this.entityCode = entityCode;
    }
    public String getEntityName() {
        return entityName;
    }
    public void setEntityName(String entityName) {
        this.entityName = entityName;
    }
    public Integer getSeqNo() {
        return seqNo;
    }
    public void setSeqNo(Integer seqNo) {
        this.seqNo = seqNo;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getEditor() {
        return editor;
    }
    public void setEditor(String editor) {
        this.editor = editor;
    }
    public Integer getLength() {
        return length;
    }
    public void setLength(Integer length) {
        this.length = length;
    }
    public String getFormat() {
        return format;
    }
    public void setFormat(String format) {
        this.format = format;
    }
    public String getVerify() {
        return verify;
    }
    public void setVerify(String verify) {
        this.verify = verify;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public String getOption() {
        return option;
    }
    public void setOption(String option) {
        this.option = option;
    }
    public String getDefaultValue() {
        return defaultValue;
    }
    public void setDefaultValue(String defaultValue) {
        this.defaultValue = defaultValue;
    }
    public Integer getAllowNull() {
        return allowNull;
    }
    public void setAllowNull(Integer allowNull) {
        this.allowNull = allowNull;
    }
    public Integer getAllowMulti() {
        return allowMulti;
    }
    public void setAllowMulti(Integer allowMulti) {
        this.allowMulti = allowMulti;
    }
    public Integer getIsdyn() {
        return isdyn;
    }
    public void setIsdyn(Integer isdyn) {
        this.isdyn = isdyn;
    }
    public Integer getIsHidden() {
        return isHidden;
    }
    public void setIsHidden(Integer isHidden) {
        this.isHidden = isHidden;
    }
    public Integer getIsSpare() {
        return isSpare;
    }
    public void setIsSpare(Integer isSpare) {
        this.isSpare = isSpare;
    }
}

